import { _decorator, Component, EditBox, Button, Label, director, Color } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('LoginManager')
export class LoginManager extends Component {
    @property(EditBox)
    usernameInput: EditBox = null;

    @property(EditBox)
    passwordInput: EditBox = null;

    @property(Button)
    loginButton: Button = null;

    @property(Label)
    messageLabel: Label = null;

    private readonly API_BASE = 'http://112.124.99.204:3000';

    onLoad() {
        // 移除自动跳转，但不清除登录状态（保留用户信息）
        // 只绑定登录按钮事件
        if (this.loginButton) {
            this.loginButton.node.on(Button.EventType.CLICK, this.onLoginClick, this);
        }
    }

    async onLoginClick() {
        if (!this.usernameInput || !this.passwordInput) {
            this.showMessage('请输入用户名和密码', true);
            return;
        }

        const username = this.usernameInput.string.trim();
        const password = this.passwordInput.string.trim();

        if (!username || !password) {
            this.showMessage('请输入用户名和密码', true);
            return;
        }

        this.showMessage('登录中...', false);
        this.setLoginButtonState(false);

        try {
            const response = await fetch(`${this.API_BASE}/api/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            const result = await response.json();
            
            if (result.success) {
                // 保存用户信息（用于游戏中的分数提交）
                localStorage.setItem('userId', result.user.id.toString());
                localStorage.setItem('username', result.user.username);
                
                this.showMessage('登录成功！', false);
                setTimeout(() => {
                    director.loadScene('scene1'); // 跳转到游戏场景
                }, 1000);
            } else {
                this.showMessage('登录失败: ' + result.message, true);
                this.setLoginButtonState(true);
            }
        } catch (error) {
            this.showMessage('网络错误，请检查服务器连接', true);
            this.setLoginButtonState(true);
            console.error('登录错误:', error);
        }
    }

    private showMessage(text: string, isError: boolean = true) {
        if (this.messageLabel) {
            this.messageLabel.string = text;
            this.messageLabel.color = isError ? new Color(255, 0, 0) : new Color(0, 0, 0);
        }
    }

    private setLoginButtonState(enabled: boolean) {
        if (this.loginButton) {
            this.loginButton.interactable = enabled;
        }
    }
}